package com.lxq.LeetCode.rotateRight;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        return " " + val +
                ", " + next
                ;
    }
}

public class Solution {
    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, null)))));
        System.out.println(rotateRight(head, 2).toString());
    }

    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        int listLength = 0;
        ListNode pHead = new ListNode();
        pHead.next = head;
        ListNode p1 = pHead, p2 = pHead.next;
        while (p1.next != null) {
            listLength++;
            p1 = p1.next;
        }
        k %= listLength;
        if (k == 0) {
            return pHead;
        }
        p1.next = pHead.next;
        for (int i = 1; i < listLength - k; i++) {
            p2 = p2.next;
        }
        pHead = p2.next;
        p2.next = null;
        return pHead;
    }
}
